package phone.qyg.com.qyg.fragment.course.detail;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecyclerViewItemDecoration;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseFragment;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.PromptManager;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.liaoinstan.springview.container.AliFooter;
import com.liaoinstan.springview.container.AliHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.MessageFormat;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.activity.CourseInterLocuOneActivity;
import phone.qyg.com.qyg.activity.CourseReleaseInterlocuActivity;
import phone.qyg.com.qyg.model.CourseInterTrans;
import phone.qyg.com.qyg.model.CourseInterlocu;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2017/12/11 16:53
 * 邮箱：lanbuhan@163.com
 * 功能：问答 笔记使用布局
 */

public class InterlocutionFragment extends BaseFragment {

    String ONE = "<font color='#ff6633'>{0}</font>";

    static String courseID;//课程id

    @ViewInject(R.id.linear)
    RelativeLayout linear;

    BaseViewStateLayout baseView;

    RecyclerView recycler;

    CommonAdapter adapter;

    SpringView springview;

    List<CourseInterlocu> models;

    boolean isForce;

    int page_no,totalpage;


    public static final InterlocutionFragment newInstance(String courseID){
        InterlocutionFragment fragment = new InterlocutionFragment();
        Bundle bundle = new Bundle();
        bundle.putString(AppHttpKey.COURSE_ID, courseID);
        InterlocutionFragment.courseID = courseID;
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View initView(LayoutInflater inflater) {
        View view = View.inflate(QXApplication.getContext(), R.layout.course_interlocu,null);
        x.view().inject(this,view);
        return view;
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        if (isRequestStr(courseID)) {
            courseID = getArguments().getString(AppHttpKey.COURSE_ID);
        }

        baseView = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_spring_recycler,null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
                LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
                layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
                recycler.addItemDecoration(new RecyclerViewItemDecoration(
                            RecyclerViewItemDecoration.MODE_HORIZONTAL, getResources().getColor(R.color.divider),
                            CommonUtil.dip2px(QXApplication.getContext(),1),0,0));
                recycler.setLayoutManager(layoutVerManager);

                springview = (SpringView) sucessView.findViewById(R.id.springview);

                springview.setListener(new SpringView.OnFreshListener() {
                    @Override
                    public void onRefresh() {
                        isForce = true;
                        getInitNetwork(false);
                    }

                    @Override
                    public void onLoadmore() {
                        if(isRequestList(models) && (page_no < totalpage) ){
                            getInitNetwork(true);
                        }else{
                            PromptManager.showToast(R.string.more_no_datas);
                            springview.onFinishFreshAndLoad();
                        }

                    }
                });

                springview.setHeader(new AliHeader(QXApplication.getContext(),false));
                springview.setFooter(new AliFooter(QXApplication.getContext(),false));
                return sucessView;
            }

            @Override
            public Object obtionData() {
                return DELFAUTSTATE;
            }
        };

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseView,layoutParams);
        x.view().inject(linear);

        View addInterlocu = View.inflate(QXApplication.getContext(),R.layout.course_add_interlocu,null);


        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = CommonUtil.dip2px(QXApplication.getContext(),100);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        linear.addView(addInterlocu,1,params);

        addInterlocu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //全局回复
                CourseInterTrans trans = new CourseInterTrans(Integer.valueOf(courseID),ApplicationConfig.COURSE_INTER);
                TransformController.transformControllerModel(QXApplication.getContext(), CourseReleaseInterlocuActivity.class,trans);
            }
        });

        isSendInter();
    }

    private void isSendInter(){
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(QXApplication.getContext());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ApplicationConfig.APP_QX_COURSE_INTER);
        BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                getInitNetwork(false);
            }
        };
        broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //可见时执行的操作
            getInitNetwork(false);
        }
    }

    /**
     * 执行网络请求
     */
    private void getInitNetwork(final boolean isPull){

        if(isPull){
            page_no = page_no + 1;
        }else{
            page_no = 1;
        }

        if(isForce){
            page_no = 1;
        }

        fMapKeys.put(AppHttpKey.TYPE,"2");
        fMapKeys.put(AppHttpKey.COURSE_ID,courseID);
        fMapKeys.put(AppHttpKey.PAGE_NO,String.valueOf(page_no));
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.COURSE_DETAIL,
                fMapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        springview.onFinishFreshAndLoad();
                        if(isState && JSONTool.isStatus(result)){
                            List<CourseInterlocu> temps = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.QUE_LIST, CourseInterlocu.class);

                            totalpage = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTALPAGE);

                            if(!isRequestList(temps) && !isPull){
                                baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
                                baseView.stateView();
                                return;
                            }
                            //成功获取到数据
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
                            baseView.stateView();

                            setModelData(isPull,temps);
                        }else{
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_ERROE);
                            baseView.stateView();
                        }
                    }
                });
    }

    private void setModelData(final boolean isPull, List<CourseInterlocu> temps) {
        if ((adapter == null && isRequestList(temps)) || isForce) {
            isForce = false;

            //数据初始化工作
            models = temps;

            final CommonAdapter adapter = new CommonAdapter<CourseInterlocu>(QXApplication.getContext(),R.layout.course_item_interlocu,models) {
                @Override
                protected void convert(ViewHolder holder, final CourseInterlocu model, int position) {

                    holder.setText(R.id.item_title,model.title);
                    holder.setText(R.id.item_name,model.user_name);
                    holder.setText(R.id.item_address,model.create_date);
                    holder.setText(R.id.item_reply, MessageFormat.format(QXApplication.getContext().getResources().getString(R.string.reply_count),
                                                        String.valueOf(model.ansCount)));

                    String content = model.atitle;
                    if(isRequestStr(content)){
                        StringBuffer buffer = new StringBuffer("");
                        String auser_name = model.auser_name;
                        String ansName = model.ans_name;

                        String buffStr = buffer.append(QXApplication.getContext().getResources().getString(R.string.new_interlou)).
                                append(" ").append(auser_name).append(" ").append(content).toString();

                        if(isRequestStr(ansName) && auser_name.contains(ansName)){
                            buffStr = buffStr.replace(ansName,MessageFormat.format(ONE,ansName));
                        }
                        holder.setTextHTMLTwo(R.id.item_content,buffStr);
                    }

                    holder.setVisible(R.id.item_content,isRequestStr(content)?true:false);


                    holder.setOnClickListener(R.id.item_my_reply, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CourseInterTrans trans = new CourseInterTrans(Integer.valueOf(model.id),ApplicationConfig.COURSE_INTER_ONE);
                            TransformController.transformControllerModel(QXApplication.getContext(),CourseReleaseInterlocuActivity.class,trans);
                        }
                    });
                }
            };

            adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    Object obj = adapter.getData().get(position);
                    TransformController.transformControllerModel(QXApplication.getContext(), CourseInterLocuOneActivity.class,obj);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });

            recycler.setAdapter(adapter);
        }

        if (isPull && isRequestList(models) && isRequestList(temps)) {
            //上拉加载数据
            models.addAll(temps);
        }

//        //刷新数据
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }

    @Override
    public void onNetChange(int netMobile) {}
}
